const { Service } = require("egg")
class BookService extends Service {
  async list(pageSize, pageNum, where) {
    const data = await this.app.mysql.select("egg_book", {
      where,
      orders: [
        ["id", "desc"],
        ["create_time", "desc"],
      ], // 排序方式
      offset: (pageNum - 1) * pageSize,
      limit: pageSize,
    })
    const total = await this.app.mysql.count("egg_book", where)
    return { data, total }
  }
  //查询是否存在相同的书籍数据
  async isExist(title) {
    console.log(title, typeof title)
    const exists = await this.app.mysql.query(
      `SELECT egg_book.title FROM egg_book WHERE title LIKE ?`,
      [title]
    )
    console.log("是否存在相同内容", exists)
    return exists
  }
  async single(id) {
    console.log(id, typeof id)
    const result = await this.app.mysql.get("egg_book", { id })
    return result
  }
  async create(book, categoryId) {
    const result = await this.app.mysql.insert("egg_book", book)
    const categoryDate = {
      book_id: result.insertId,
      category_id: categoryId,
    }
    const category_result = await this.app.mysql.insert(
      "egg_book_category",
      categoryDate
    )
    return result
  }
  async update(book) {
    const result = await this.app.mysql.update("egg_book", book)
    return result
  }
  async destroy(id) {
    const result = await this.app.mysql.delete("egg_book", { id })
    return result
  }
  //修改图书分类
  async editCateGory(data) {
    const result = await this.app.mysql.query(
      `update egg_book_category set category_id=? where book_id=?`,
      [data.category_id, data.book_id]
    )
    return result
  }
}
module.exports = BookService
